define(function(require){
	
	var $=require("jq");
	var Dialog=require("pz_use_dialog.js");
	var dialogs={
		error:function(msg){
			var tip=new Dialog({
						 type:"alert",
						  height:107,
						  tipsText:msg,
						  buttonSureText:"知道了", 
						  mask:"transparent",
						  isDrag:true              
		        	});
		}
	};
	
		var itemList=$("#order-cart-wrap");
						
	function creatOrderGoodsList(/*addStr*/){
		location="/cartList.do?operateParam="+Math.random();
	}
		
		after();
	function after(){
		function updateNumInput() {
			var tempTime=null;
			var alertShowState=false;
		
			$(".wrap-input .text").blur(function(e){
					var _this=this;
					var _this$=$(_this);
						var amount=_this.value;
						var id=$(_this).parent().parent().parent().attr("cartItem_serials");
						if(/^\d+$/.test(amount+"")){
							//将其发送值的请求延时执行，解决失去加点点击加号同事触发的bug
							function delayRun(){
								$.get("/updateItem.do?rand="+Math.random(),{amount:amount,cartItem_serial:id},function(json){
									if(json.state=="error"){
										dialogs.error(json.msg);
										_this$.val(_this$.data("curTureVal"));
									}else{
										creatOrderGoodsList();
									}
								},"json");
							}
							window.setTimeout(delayRun,300);
						}else{
							_this$.val(_this$.data("curTureVal"));
						}
//				if(e.which!=13){
//					var _this=this;
//					window.clearTimeout(tempTime);
//					tempTime=window.setTimeout(function(){
//						var amount=_this.value;
//						var id=$(_this).parent().parent().parent().attr("cartItem_serials");
//						if(/\d+/.test(amount+"")){ 
//							$.get("/updateItem.do",{amount:amount,cartItem_serial:id},function(json){
//								if(json.state=="error"){
//									dialogs.error(json.msg);
//								}else{
//									creatOrderGoodsList();
//								}
//							},"json");
//						}
//					},300);
//				};
			}).focus(function(){
				$(this).data("curTureVal",this.value);
			});
		}
		
		updateNumInput();
		

		//绑定删除所有物件
		$("#deleteAll").on("click",function(){
			deleteAll();
		});
		
		
		
		
		$('#toggle-checkboxes').on("click",function(){

				var itemChecked = $("input[name='checkItem']");
				
				if (this.checked) {

					
					if (itemChecked.checked) {


					}
					itemChecked.prop("checked", true);
				}

				else{

					itemChecked.prop("checked", false);

				}
				

		});


		//减少商品数量
	    $("[id^='decrement-']").on("click", function(event){
	        minusSkuNum(this);
	    });
	    
	    //增加商品数量
	    $("[id^='increment-']").on("click", function(event){
	        addSkuNum(this);
	    });
	    $("[id^='deleteItem-']").on("click", function(event){
	    	$('#del-layer').data("deleteObj",this);
	    	var top = $(this).offset().top,
				left =$(this).offset().left;
			delLayer(top,left);
	    });

		//删除弹出层

		var delLayer = function(x,y){
			$('.del-layer').css({
				"top": x - (100),
				"left":y - (90)
			}).fadeIn();

		}


		// 取消弹出曾
		
		$('#del-goods-f').on("click",function(){

			$('.del-layer').hide();
		});
		
		//删除物品
		$('#del-goods-t').on("click",function(){
				deleteItem($("#del-layer").data("deleteObj"));
				$('.del-layer').hide();
		});
	
		$(".showExchange").on("click",function(){
			
		});
		
		/**
		 * 换赠弹窗
		 */		
		function ExchangeGift(){
			var _this=this;
			this.win=$("#select-gift");
			this.closeButton=this.win.find(".close-gift").on("click",function(){
				_this.close();
			});
			this.giftList=this.win.find(".select-gift-content");
		}
		
		ExchangeGift.prototype={
			setData:function (url,obj){
				this.obj=$(obj);
				this.x=this.obj.offset().top;
				this.y=this.obj.offset().left;
				this.orderPresentRuleId=this.obj.attr("data-id");
				this.url=url;
			},
			opean:function(url,obj){
				this.setData(url,obj);
				this.show();
				this.sendRequest();
			},
			sendRequest:function(url){
				var _this=this;
				$.get(this.url,{orderPresentRuleId:this.orderPresentRuleId},function(html){
					_this.getResp(html);
				});
			},
			getResp:function(html){
				this.giftList.html(html);

				//让容器尽情伸展
				this.giftList.css("height","auto");
				//根据高度判断
				if(this.giftList.height()>400){
					this.giftList.css("height","320px");
				}else{
					this.giftList.css("height","auto");
				}
				this.giftEventBlind();
				
			},
			giftEventBlind:function(){
				var _thisO = this;
				$(".del-goods-t").on("click",function(){
					var _this=$(this);
					var data_gift_canbuy = _this.attr('data-gift-canbuy');
					if(data_gift_canbuy == 'false'){
						var tip=new Dialog({
							 type:"alert",
							  height:107,
							  tipsText:'对不起您选择的赠品暂时无货',
							  buttonSureText:"知道了", 
							  mask:"transparent",
							  isDrag:true              
			        	});
						_thisO.close();
						return;
					}
					$.get("/selectGift.do?rand="+Math.random(),{"ruleId":_this.attr("data-rule-id"),giftId:_this.attr("data-gift-id")},function(){
						creatOrderGoodsList();
					});
				});
			},
			close:function(){
				this.giftList.html("正在加载中....");
				this.hide();
			},
			show:function(x,y){
				this.giftList.html("正在加载中....");
				this.win.css({
					"top": this.x + (40),
					"left":this.y - (90)
				}).fadeIn();
			},
			hide:function(){
				this.win.hide();
			}
		}
		var exchangeGiftWin=new ExchangeGift();
		$(".showExchange").on("click",function(){
			exchangeGiftWin.opean("/orderGifts.do",this);
		});
		
		
		

		function CheckManager(url){
			var _this=this;
			this.url=url;
			this.selectAllButton=$("#selectAll");
			this.selectButtons=$(".checkboxItem");
			this.selectAllButton.click(function(){
				_this.changeAll();
				_this.sendRequest();
			});
			this.selectButtons.click(function(){
				_this.sendRequest();
			});
		}
		
		CheckManager.prototype={
			changeAll:function(){
				var checked=this.selectAllButton.get(0).checked;
					this.selectButtons.each(function(){
						this.checked=checked
					});
			
			},
			sendRequest:function(){
				var _this=this;
				$.get(this.url+"?rand"+Math.random(),{cartitem_serials:this.getIdsWithCheck()},function(){
					_this.dealRespone();
				});
			},
			dealRespone:function(){
				creatOrderGoodsList();
			},
			getIdsWithCheck:function(){
				var _this=this;
				var ids="";
				this.selectButtons.each(function(){
					if(this.checked){
						ids+=_this.getIdbyObj(this)+",";
					}
				});
				ids=ids.substring(0,ids.length-1);
				return ids;
			},
			getIdbyObj:function (obj){
				return $(obj).parent().parent().attr('cartitem_serials');
			},
			init:function(){
				if(this.getIdsWithCheck()==""){
					if(this.selectAllButton.length>0){
						this.selectAllButton.get(0).checked=false;
					}
				};
			}
		}
		checkManager=new CheckManager("/updateChecked.do");
		checkManager.init();
		
		function OrderGiftManager(){
			$(".exchangeGroup").each(function(){
				var _this=$(this);
				if(_this.find(".orderGift").length!=0){
					_this.find(".showExchange").html("重选");
				}
			});
		
		};
		OrderGiftManager();
		
		/**
		 * 去结算
		 */
		 function gotoAccount(){
		 	$(".gotoAccount").on("click",function(){
		 		if($(this).hasClass("disable")){
		 			return ;
		 		}
		 			var ids="";
			 		$(".checkboxItem").each(function(){
			 			if(this.checked){
							ids=ids+$(this).parent().parent().attr('cartitem_serials')+",";
						}
			 		});
			 		ids=ids.substring(0,ids.length-1);
			 		window.location="/order.do?cartitem_serials="+ids;
		 	})
		 }
		 gotoAccount();
		//增加商品数量
		 function addSkuNum(obj){
		    var skuNum = $(obj).next(),
		        val = skuNum.val(),//更新商品的数量
		        cartItem_serial = $(obj).parents("tr").attr('cartitem_serials');//购物车序列号码

		        var amount = parseInt(val) + parseInt('1');
		    	var url = "/updateItem.do";
		        $.post(url,{cartItem_serial:cartItem_serial,amount:amount},function(msg){
		        	var state = msg.state;
		        	if(state== 'error'){//更新购物车失败
		        		
		        	var tip=new Dialog({
						 type:"alert",
						  height:107,
						  tipsText:msg.msg,
						  buttonSureText:"知道了", 
						  mask:"transparent",
						  isDrag:true              
		        	});
		        		return;
		        	}else{//更新购物车成功
		        		creatOrderGoodsList(msg.shoppingCart);//刷新列表
		        	}
		        },"json");
		 }

		 /**减少商品数量**/
		 function minusSkuNum(obj){
		    var skuNum = $(obj).next().next(),
		        val = skuNum.val(),
			    cartItem_serial =  $(obj).parents("tr").attr('cartitem_serials');//购物车序列号码
		        if (parseInt(val)<=1) {
		        	//dialogs.error("商品数量不能小于1");
		            return;
		        };
		        var amount = parseInt(val) - parseInt('1');
		    	var url = "/updateItem.do";
		        $.post(url,{cartItem_serial:cartItem_serial,amount:amount},function(msg){
		        	var state = msg.state;
		        	if(state == 'error'){//更新购物车失败
		        		dialogs.error(msg.msg);
		        		return;
		        	}else{//更新购物车成功
		        		creatOrderGoodsList(msg.shoppingCart);//刷新列表
		        	}
		        },"json");
		 }
		 /**删除物件**/
		 function deleteItem(obj){
		 	 var cartItem_serial=$(obj).parents("tr").attr('cartitem_serials');
		 	  var url = "/deleteItem.do";
			$.post(url,{cartItem_serials:cartItem_serial},function(msg){
				var state = msg.state;
				if(state == 'error'){//更新购物车失败
					dialogs.error(msg.msg);
					return;
				}else{//更新购物车成功
					creatOrderGoodsList();//刷新列表
				}
			},"json");
		 }
		 /**删除所有物件**/
		 function deleteAll(){
		 	var ids="";
		 	var count=0;
			$(".checkboxItem").each(function(){
				if(this.checked){
					count++;
					ids=ids+$(this).parent().parent().attr('cartitem_serials')+",";
				}
			});
			
			if(count==0){
				dialogs.error("请选择要删除的商品");
				return;
			}
			
			
			ids=ids.substring(0,ids.length-1);
		 	var url="/deleteItem.do";
			$.post(url,{cartItem_serials:ids},function(msg){
				var state = msg.state;
				if(state == 'error'){//更新购物车失败
					dialogs.error(msg.msg);
					return;
				}else{//更新购物车成功
					creatOrderGoodsList();//刷新列表
				}
			},"json");
		 }
		
	}	

});
